package xyz.itpath.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import xyz.itpath.config.OssProperties;
import xyz.itpath.entity.OssFile;
import xyz.itpath.mapper.OssFileMapper;
import xyz.itpath.service.IOssFileService;
import xyz.itpath.service.OssService;

import java.io.InputStream;
import java.time.Duration;
import java.util.Map;

/**
 * @author zhaomengru
 * create by 2024/1/3 - 21:17
 */
@Service
@RequiredArgsConstructor
public class OssFileServiceImpl extends ServiceImpl<OssFileMapper, OssFile> implements IOssFileService {

    private final OssProperties properties;
    private final OssService ossService;

    @Override
    public OssFile uploadFile(InputStream inputStream, String fileName, String bucketName) {
        String md5sum = ossService.upload(inputStream, fileName);
        OssFile ossFile = createOssFile(fileName, bucketName, md5sum);
        save(ossFile);
        return ossFile;
    }

    @Override
    public String stsToken(Long fileId, Duration duration, Map<String, String> headers) {
       return ossService.getUrl(getOssFile(fileId).getFileName(), duration);
    }

    @Override
    public InputStream downloadFile(Long fileId) {
        return ossService.download(getOssFile(fileId).getFileName());
    }

    @Override
    public void deleteFile(Long fileId) {
        OssFile ossFile = getOssFile(fileId);
        ossService.delete(ossFile.getFileName());
        removeById(fileId);
    }

    private OssFile getOssFile(Long fileId) {
        OssFile ossF = getById(fileId);
        Assert.notNull(ossF, "指定的文件不存在");
        return ossF;
    }

    private OssFile createOssFile(String fileName, String bucketName, String md5sum) {
        OssFile ossFile = new OssFile();
        ossFile.setFileName(fileName);
        ossFile.setBucketName(bucketName);
        ossFile.setMd5sum(md5sum);
        ossFile.setOssType(properties.getOssType());
        return ossFile;
    }
}
